﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using DunLibrary.Dun;
using DunSilverlight.Comm;
using Telerik.Windows.Controls;
using DunLibrary.CreditCard;
using System.Windows.Data;

namespace DunSilverlight.Views
{
    /// <summary>
    /// 外访申请(记录)记录详细信息
    /// </summary>
    public partial class VisitForm : UserControl
    {
        private VisitRecord visitRecord;
        private IList<DunLibrary.CreditCard.CardholderContact> contacts;

        private IList<DunLibrary.User.User> visitors;

        public Action<VisitRecord> SaveCallBack;

        public VisitForm(VisitRecord vr)
        {
            visitRecord = vr;
            //this.contacts = contacts;
            VisitRightToEnable.VisitRecord = vr;
            InitializeComponent();
            Loaded += new RoutedEventHandler(VisitForm_Loaded);
        }

        void VisitForm_Loaded(object sender, RoutedEventArgs e)
        {
            DataContext = visitRecord;
            LoadVisitors();
            LoadChecker();//获得有审核权的人员名单
            LoadAddress();//获取可用地址列表

            Action<IList<DunLibrary.Dun.ReceiveTypeOfCall>> callBack = (IList<DunLibrary.Dun.ReceiveTypeOfCall> types) =>
                {
                    cmbReciveType.ItemsSource = types;
                };

            AppGlobal.GetReceiveTypeCalls(callBack);
        }

        private void btnAddUser_Click(object sender, RoutedEventArgs e)
        {
            if (visitRecord.Id == 0)
            {
                Tools.ShowMessage("请先保存外访记录!", "", false);
            }
            else
            {
                Action<DunLibrary.User.User> selectedCallBack = (DunLibrary.User.User u) =>
                    {
                        SaveAddVisitor(u.Id);
                    };

                Action<IList<DunLibrary.User.User>> getUserCallBack = (IList<DunLibrary.User.User> users) =>
                    {
                        UserListForm frm = new UserListForm();
                        frm.Users = users;
                        frm.SelectedCallBack = selectedCallBack;

                        Tools.OpenWindow("选择外访人员", frm, null,360,400);
                    };
                GetUsers(getUserCallBack);
            }
        }
        /// <summary>
        /// 将添加的外访用户保存到服务器
        /// </summary>
        private void SaveAddVisitor(int userId)
        {
            try
            {
                VisitRecordService.VisitRecordServiceClient ser = new VisitRecordService.VisitRecordServiceClient();

                ser.AddVisitorCompleted += (object sender, VisitRecordService.AddVisitorCompletedEventArgs e) =>
                    {
                        LoadVisitors();
                    };
                ser.AddVisitorAsync(visitRecord.Id, userId);
            }
            catch (Exception ex)
            {
                Tools.ShowMessage(ex.Message, "", false);
            }
            
        }
        /// <summary>
        /// 删除一个外访人员
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDeleteUser_Click(object sender, RoutedEventArgs e)
        {
            DunLibrary.User.User u = dgdVisitors.SelectedItem as DunLibrary.User.User;

            if (u != null)
            {
                VisitRecordService.VisitRecordServiceClient ser = new VisitRecordService.VisitRecordServiceClient();
                 ser.DelVisitorCompleted += (object sender1, VisitRecordService.DelVisitorCompletedEventArgs e1) =>
                    {
                        bool b=JsonSerializerHelper.JsonToEntity<bool>(e1.Result);

                        if(b)
                        {
                            LoadVisitors();
                        }
                    };
                 ser.DelVisitorAsync(visitRecord.Id, u.Id);
            }
        }
        /// <summary>
        /// 读取所有外访人员的列表
        /// </summary>
        private void LoadVisitors()
        {
            UserService.UserServiceClient ser = new UserService.UserServiceClient();

            ser.GetListByHQLCompleted += (object sendser, UserService.GetListByHQLCompletedEventArgs e) =>
                {
                    try
                    {
                        int totalCount = 0;
                        IList<DunLibrary.User.User> users = JsonSerializerHelper.JsonToEntities<DunLibrary.User.User>(e.Result, out totalCount);

                        dgdVisitors.ItemsSource = users;
                    }
                    catch (Exception ex)
                    {
                        Tools.ShowMessage(ex.Message, "", false);
                    }
                };

            string hql = "select u from VisitRecord as v left join v.Visitors as u where v.Id=" + visitRecord.Id;

            ser.GetListByHQLAsync(hql);
        }

        /// <summary>
        /// 获取本部门所有有外访审核权限的用户
        /// </summary>
        private void LoadChecker()
        {
            UserService.UserServiceClient ser = new UserService.UserServiceClient();
            ser.GetListByHQLCompleted += (object sender, UserService.GetListByHQLCompletedEventArgs e) =>
                {
                    int totalCount = 0;

                    IList<DunLibrary.User.User> user = JsonSerializerHelper.JsonToEntities<DunLibrary.User.User>(e.Result, out totalCount);

                    cmbChecker.ItemsSource = user;
                };

            string hql = string.Format("select u from User as u inner join u.Role as r left join r.Rights as t where t.Number='{0}' and u.Organization.Id={1}", RightManagement.Right_Visits_Check,AppGlobal.CurrentUser.Organization.Id);

            ser.GetListByHQLAsync(hql);
        }
        /// <summary>
        /// 获取地址
        /// </summary>
        private void LoadAddress()
        {
            CardholderContactService.CardholderContactServiceClient ser = new CardholderContactService.CardholderContactServiceClient();

            ser.GetListByHQLCompleted += (object sender, CardholderContactService.GetListByHQLCompletedEventArgs e) =>
            {
                try
                {
                    int totalCount = 0;

                    IList<CardholderContact> cs = JsonSerializerHelper.JsonToEntities<CardholderContact>(e.Result, out totalCount);

                    cmbAddress.ItemsSource = cs;
                }
                catch (Exception ex)
                {
                    Tools.ShowMessage(ex.Message, "", false);
                }
            };
            //NHibernate这里有个bug,不能直接使用Case属性名,必须给对象一个别名，然后再用.
            ser.GetListByHQLAsync("from CardholderContact as c where c.ContactType.Id=2 and Owner.Id =" + visitRecord.Case.Holder.Id);
        }

        /// <summary>
        /// 保存前验证
        /// </summary>
        /// <returns></returns>
        private bool CheckVerify()
        {
            if (!visitRecord.IsAllow)//判断是否审核
            {
                if (!string.IsNullOrEmpty(visitRecord.Contact))
                {
                    Tools.ShowMessage("请填写外访地址!", "", false);
                    return false;
                }
                if (visitRecord.CallTime == null)
                {
                    Tools.ShowMessage("请填写外访时间!", "", false);
                    return false;
                }

                if (string.IsNullOrEmpty(visitRecord.RequestContent))
                {
                    Tools.ShowMessage("请填写外访理由!", "", false);
                    return false;
                }
            }

            return true;
        }
        /// <summary>
        /// 获取所有本部门所有用户
        /// </summary>
        /// <returns></returns>
        private void GetUsers(Action<IList<DunLibrary.User.User>> callBack)
        {
            UserService.UserServiceClient ser = new UserService.UserServiceClient();

            ser.GetListByHQLCompleted += (object sender1, UserService.GetListByHQLCompletedEventArgs e) =>
                {
                    int totalCount = 0;

                    IList<DunLibrary.User.User> users=JsonSerializerHelper.JsonToEntities<DunLibrary.User.User>(e.Result,out totalCount);

                    callBack(users);
                };

            string hql=string.Format("select u from User as u where u.Organization.Id={0}",AppGlobal.CurrentUser.Organization.Id);

            ser.GetListByHQLAsync(hql);
        }


        private void SetRightControl()
        {
            //当前用户有没有审核权
            if (RightManagement.VerifyRight(RightManagement.Right_Visits_Check))
            {

            }
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            ////测试
            //visitRecord.Visitors = new List<DunLibrary.User.User>();
            //visitRecord.Visitors.Add(AppGlobal.CurrentUser);

            VisitRecordService.VisitRecordServiceClient ser = new VisitRecordService.VisitRecordServiceClient();

            ser.SaveOrUpdateCompleted += (object sender1, VisitRecordService.SaveOrUpdateCompletedEventArgs e1) =>
                {
                    int id = Comm.JsonSerializerHelper.JsonToEntity<int>(e1.Result);
                    visitRecord.Id = id;

                    if (SaveCallBack != null)
                        SaveCallBack(visitRecord);//保存成功后回调
                };

            string json=Newtonsoft.Json.JsonConvert.SerializeObject(visitRecord);

            ser.SaveOrUpdateAsync(json);
        }
        /// <summary>
        /// 退出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExit_Click(object sender, RoutedEventArgs e)
        {
            (this.Parent as RadWindow).Close();
        }
    }


}
